<?
    // server script for gitbook games
    // authon: guoxiaomi
    // verison 0.2
    // use memcached

    // get & post
    $callback = $_GET['jsoncallback'];
    $key_load = $_GET['load'];

    $key_update = $_POST['update'];
    $force = ($_POST['force'] != '0');
    if ($_POST['value']) {
        $value = json_decode($_POST['value'], true);
    }

    // init memcached
    $mmc = new Memcached();
    $expiration = 86400;

    if ($key_load) {
        $db = $mmc->get($key_load);
        // return db
        die($callback.'('.json_encode($db).')');
    }

    if ($key_update && $force) {
        $mmc->set($key_update, $value, $expiration);
    }

    if ($key_update && !$force) {
        $db = $mmc->get($key_update);
        if ($db === false) {
            $db = [];
        }

        foreach ($value as $k => $v) {
            switch ($k) {
                case '_add_':
                    foreach ($v as $k_add => $v_add) {
                        $db[$k_add] = array_values(array_merge($db[$k_add], $v_add));
                    }
                    break;
                case '_del_':
                    foreach ($v as $k_del => $v_del) {
                        $db[$k_del] = array_values(array_diff($db[$k_del], $v_del));
                    }
                    break;
                default:
                    $db[$k] = $v;
                    break;
            }
        }
        $mmc->set($key_update, $db, $expiration);
    }
?>